package com.ctg.itrdc.sysmgr.permission.core.sso;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

/**
 * 存储ticket到sessionID的映射
 */
public final class HashMapBackedMappingStorage {
	
    private final Map<String,Subject> recordedSubjects = new HashMap<String,Subject>();

	public void addSubject(String mappingId, Subject subject) {
		synchronized(recordedSubjects) {
			recordedSubjects.put(mappingId, subject);
		}

	}                               

	public Subject getSubjectByMappingId(String mappingId) {
		synchronized(recordedSubjects) { 
			return recordedSubjects.get(mappingId);
		}
	}
	
	public void removeSubjectByMappingId(String mappingId) {
		synchronized(recordedSubjects) {
			recordedSubjects.remove(mappingId);
		}
	}
	
	public void removeSubjectBySessionId(String sessionId) {
		synchronized(recordedSubjects) {
			List<String> keyToDelete = new ArrayList<String>();
			for(String key : recordedSubjects.keySet()) {
				Subject s = recordedSubjects.get(key);
				Session session = s.getSession(false);
				if(session != null) {
					String sId = session.getId().toString();
					if(sId.equals(sessionId)) {
						keyToDelete.add(key);
						continue;
					}
				}
				try {
					// 如果存在没有任何身份信息的subject，也将其删除
					PrincipalCollection principals = s.getPrincipals();
					if(principals == null || principals.isEmpty()) {
						keyToDelete.add(key);
					}
				} catch (InvalidSessionException e) {// 存在已过期的session
					keyToDelete.add(key);
				}
			}
			
			for(String key : keyToDelete) {
				recordedSubjects.remove(key);
			}
		}
	}
}
